/**
 * 
 */
package com.md.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.md.Filter;
import com.md.entity.TestLock;
import com.md.model.BaseModel;
import com.md.model.StandardListModel;
import com.md.service.BaseService;
import com.md.util.JsonSerializer;

/**
 * @author yehao
 *
 */
public abstract class StandardListController<T> extends BaseController {

	private Map<String, Object> pageResult = new HashMap<>();

	private PageInfo<T> pageInfo;


	public PageInfo<T> getPageInfo() {
		return pageInfo;
	}

	public void setPageInfo(PageInfo<T> pageInfo) {
		this.pageInfo = pageInfo;
	}

	@Override
	public void setModel() {
		BaseModel baseModel = new StandardListModel();
		if (modelMap == null) {
			modelMap = new ModelMap();
			modelMap.addAttribute("model", baseModel);
		}
	}

	@RequestMapping("/list")
	public ModelAndView list() {
		ModelAndView modelAndView = super.display();
		String[] views = modelAndView.getViewName().split("/");
		modelAndView.setViewName(views[0] + "/" + views[0] + "List");
		return modelAndView;
	}

	@RequestMapping("/delRecords")
	public @ResponseBody Map<String, String> delRecords(@RequestParam("records") String records) {
		List<TestLock> testLocks = (List<TestLock>) JsonSerializer.getDefault().deserialize(records, List.class, TestLock.class);
		testLocks.forEach(record -> {
			entityManager.remove(entityManager.merge(record));
			entityManager.flush();
		});
		return this.message("删除成功", true);
	}

	@RequestMapping("/getList")
	public @ResponseBody Map<String, Object> listData(@RequestParam Map<String, String> paramsMap) {
		PageHelper.startPage(Integer.parseInt(paramsMap.get("page")), Integer.parseInt(paramsMap.get("limit")));
		List<Filter> filters = JSON.parseArray(paramsMap.get("filters"),Filter.class);
		Map<String,Object> params = new HashMap<>();
		params.put("filters", filters);
		List<T> objectList = baseService.getObjectList("getPageList",params);
		PageInfo<T> pageInfo = new PageInfo<T>(objectList);
		pageResult.put("code", "0");
		pageResult.put("msg", "查询成功!");
		pageResult.put("data", pageInfo.getList());
		pageResult.put("count", pageInfo.getTotal());
		return pageResult;
	}
}
